<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,jvm," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="对象结构java对象由三部分组成：对象头、实例数据、对齐填充。  对象头对象头主要包括两个部分：   对象自身运行数据对象自身运行数据主要包括：Hash码、GC年龄、锁状态标志、线程持有的锁、偏向线程id、偏向时间戳等  类型指针类型指针指向对象的类元数据。虚拟机通过该指针判断对象属于什么类实例。  如果是数组对象，则还有一部分用于保存数组的长度。所以java对象的组成大致细分为如下几部分：  对">
<meta name="keywords" content="java,jvm">
<meta property="og:type" content="article">
<meta property="og:title" content="Java对象的组成，如何计算对象的大小">
<meta property="og:url" content="https://gitee.com/shuhao/2018/06/23/Java对象的组成，如何计算对象的大小/index.html">
<meta property="og:site_name" content="Niki">
<meta property="og:description" content="对象结构java对象由三部分组成：对象头、实例数据、对齐填充。  对象头对象头主要包括两个部分：   对象自身运行数据对象自身运行数据主要包括：Hash码、GC年龄、锁状态标志、线程持有的锁、偏向线程id、偏向时间戳等  类型指针类型指针指向对象的类元数据。虚拟机通过该指针判断对象属于什么类实例。  如果是数组对象，则还有一部分用于保存数组的长度。所以java对象的组成大致细分为如下几部分：  对">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://gitee.com/blog/images/java/jvm/calss_structure.png">
<meta property="og:image" content="https://gitee.com/blog/images/java/jvm/object_size_output.png">
<meta property="og:updated_time" content="2018-07-16T12:31:13.434Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java对象的组成，如何计算对象的大小">
<meta name="twitter:description" content="对象结构java对象由三部分组成：对象头、实例数据、对齐填充。  对象头对象头主要包括两个部分：   对象自身运行数据对象自身运行数据主要包括：Hash码、GC年龄、锁状态标志、线程持有的锁、偏向线程id、偏向时间戳等  类型指针类型指针指向对象的类元数据。虚拟机通过该指针判断对象属于什么类实例。  如果是数组对象，则还有一部分用于保存数组的长度。所以java对象的组成大致细分为如下几部分：  对">
<meta name="twitter:image" content="https://gitee.com/blog/images/java/jvm/calss_structure.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/shuhao/2018/06/23/Java对象的组成，如何计算对象的大小/"/>





  <title> Java对象的组成，如何计算对象的大小 | Niki </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cb9f0585e406f878cb2f29c89ad3cdb7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Niki</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天道酬勤</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-categories"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/shuhao/blog/2018/06/23/Java对象的组成，如何计算对象的大小/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Fang ShuHao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Niki">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Java对象的组成，如何计算对象的大小
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-23T10:42:50+08:00">
                2018-06-23
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="对象结构"><a href="#对象结构" class="headerlink" title="对象结构"></a>对象结构</h2><p>java对象由三部分组成：对象头、实例数据、对齐填充。</p>
<ul>
<li>对象头<br>对象头主要包括两个部分：</li>
</ul>
<ol>
<li><p>对象自身运行数据<br>对象自身运行数据主要包括：<strong>Hash码</strong>、<strong>GC年龄</strong>、<strong>锁状态标志</strong>、<strong>线程持有的锁</strong>、<strong>偏向线程id</strong>、<strong>偏向时间戳</strong>等</p>
</li>
<li><p>类型指针<br>类型指针指向对象的类元数据。虚拟机通过该指针判断对象属于什么类实例。</p>
</li>
<li><p>如果是数组对象，则还有一部分用于保存数组的长度。<br>所以java对象的组成大致细分为如下几部分：</p>
</li>
<li><p>对齐填充<br>由于HotSpot VM的自动内存管理系统要求对象起始地址必须是8字节的整数倍。所以java对象的大小必须是8字节的整数倍。所以对齐填充则是未了保证这一原则。</p>
</li>
</ol>
<ul>
<li>对象头 （4：经过压缩；8没有经过压缩）</li>
<li>类型指针</li>
<li>实例数据</li>
<li>对齐填充</li>
<li><strong><em>数组长度</em></strong> （数组对象）<img src="/blog/images/java/jvm/calss_structure.png">
</li>
</ul>
<h2 id="获取对象的大小"><a href="#获取对象的大小" class="headerlink" title="获取对象的大小"></a>获取对象的大小</h2><p>上面说到对象的组成主要分为对象头、实例数据、对齐填充。那么计算一个对象的大小，只需要将这些部分所占内存大小求和即可。那么，我们来看下这几个部分分别占内存的大小是多少：</p>
<ol>
<li>对象头：8byte</li>
<li>类型指针（Oop）： 32G内存一下，默认开启对象指针压缩。4byte</li>
<li>数据区。数据所占内存区域大小和</li>
<li>padding内存对齐：按照8倍数进行对齐</li>
</ol>
<h3 id="计算方法"><a href="#计算方法" class="headerlink" title="计算方法"></a>计算方法</h3><ol>
<li>通过Instrumentation的getObjectSize(obj)直接获取对象大小。<a href="http://shuhao.gitee.io/blog/2018/04/19/Tomcat%E4%B8%AD%E6%97%A0%E6%B3%95%E8%8E%B7%E5%8F%96Instrumentation%E5%AF%B9%E8%B1%A1%E4%B8%BAnull%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95/" target="_blank" rel="external">使用Instrumentation参考</a></li>
<li>通过sun.misc.Unsafe对象的objectFieldOffset(field) 方法结合放射计算对象大小</li>
</ol>
<h3 id="Padding规则"><a href="#Padding规则" class="headerlink" title="Padding规则"></a>Padding规则</h3><p>在计算类中字段大小时，不是等全部大小计算完毕之后添加padding对齐8的倍数。而是<strong>每添加一个字段都计算之前的内存是否是8的倍数</strong>。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo</span></span>&#123;</span><br><span class="line">	<span class="keyword">byte</span> b1;</span><br><span class="line">	<span class="keyword">int</span> i1;</span><br><span class="line">	<span class="keyword">char</span> c1;</span><br><span class="line">	String s1;</span><br><span class="line">	<span class="keyword">boolean</span> bo1;</span><br><span class="line">	<span class="keyword">int</span> i2;</span><br><span class="line">	<span class="keyword">byte</span> b2;</span><br><span class="line">	<span class="keyword">short</span> ss1;</span><br><span class="line">	<span class="keyword">byte</span> b3;</span><br><span class="line">	String s2;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个对象的大小：<br>8（mark）+ 4(oop) + 1(b1) + <strong>3(padding)</strong>+ 4(i1) +  2(c1) + <strong>2(padding)</strong> + 4(s1) + 1(bo1) + <strong>3(padding)</strong> + 4(i2) + 1(b2) + 2(ss1) + 1(b3) + 4(s2) + <strong>4(padding)</strong> = 48byte<br>然而真的是这样计算的么？</p>
<h3 id="对象字段排序"><a href="#对象字段排序" class="headerlink" title="对象字段排序"></a>对象字段排序</h3><p>HotSpotVM创建的对象的字段会按照默认的顺序进行排序。<br>double/long -&gt; float/int -&gt; char/short -&gt; byte/boolean -&gt; Reference<br>可以看到，字段排序的规则：</p>
<ol>
<li>按照字段所占内存大小，从大到小排序</li>
<li>引用类型字段排最后</li>
<li>对象字段仅计算对象引用的大小，不计算对象字段的真实大小。如有需要，进行递归计算。</li>
</ol>
<p><strong><em>根据这个规则，我们重新计算对象的大小：</em></strong><br>8（mark）+ 4(oop) + 4(i1) + 4(i2) + 2(c1) + 2(ss1) + 1(b1) + 1(b2) + 1(b3) + 1(bo1) + 4(s1)  + 4(s2) + 4(padding)  = 40byte</p>
<p>对象字段排序规则也可以通过JVM参数进行设置：<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">--XX:FieldsAllocationSylte=0 （默认是1）</span><br></pre></td></tr></table></figure></p>
<h3 id="objectFieldOffset计算对象大小"><a href="#objectFieldOffset计算对象大小" class="headerlink" title="objectFieldOffset计算对象大小"></a>objectFieldOffset计算对象大小</h3><p>Unsafe类提供方法objectFieldOffset用于计算类中每个field字段的偏移量。<br><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ObjectA</span> </span>&#123;</span><br><span class="line">	String str;  <span class="comment">// 4</span></span><br><span class="line">	<span class="keyword">int</span> i1; <span class="comment">// 4</span></span><br><span class="line">	<span class="keyword">byte</span> b1; <span class="comment">// 1</span></span><br><span class="line">	<span class="keyword">byte</span> b2; <span class="comment">// 1</span></span><br><span class="line">	<span class="keyword">int</span> i2;	 <span class="comment">// 4 </span></span><br><span class="line">	ObjectB obj; <span class="comment">//4</span></span><br><span class="line">	<span class="keyword">byte</span> b3;  <span class="comment">// 1</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Field[] fields = ObjectA.class.getDeclaredFields();</span><br><span class="line"><span class="keyword">for</span>(Field f: fields)&#123;</span><br><span class="line">	System.out.println(f.getName() + <span class="string">" offset: "</span> +unsafe.objectFieldOffset(f));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>输出<br><img src="/blog/images/java/jvm/object_size_output.png"></p>
<p>可以看出对象的offerset也是遵循对象字段排序的规则<br>field占空间： 28-12 = 16<br>对象头： 8+4 =12<br>对齐8倍数 16+12+4 = 32</p>
<p>代码参考gitee<br><a href="https://gitee.com/shuhao/code/tree/master/java-template/src/main/java/object/size">计算类大小demo</a></p>
<blockquote>
<blockquote>
<p>参考<br><a href="https://blog.csdn.net/iter_zc/article/details/41822719" target="_blank" rel="external">聊聊JVM（三）两种计算Java对象大小的方法</a></p>
</blockquote>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/java/" rel="tag"># java</a>
          
            <a href="/blog/tags/jvm/" rel="tag"># jvm</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/06/22/Spring总结/" rel="next" title="Spring随记">
                <i class="fa fa-chevron-left"></i> Spring随记
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/06/28/Java并发编程之StampedLock/" rel="prev" title="Java并发编程之StampedLock">
                Java并发编程之StampedLock <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNjY5NS8xMzIzMA=="></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/head.jpg"
               alt="Fang ShuHao" />
          <p class="site-author-name" itemprop="name">Fang ShuHao</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">135</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories">
                <span class="site-state-item-count">35</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">93</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#对象结构"><span class="nav-number">1.</span> <span class="nav-text">对象结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#获取对象的大小"><span class="nav-number">2.</span> <span class="nav-text">获取对象的大小</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#计算方法"><span class="nav-number">2.1.</span> <span class="nav-text">计算方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Padding规则"><span class="nav-number">2.2.</span> <span class="nav-text">Padding规则</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#对象字段排序"><span class="nav-number">2.3.</span> <span class="nav-text">对象字段排序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#objectFieldOffset计算对象大小"><span class="nav-number">2.4.</span> <span class="nav-text">objectFieldOffset计算对象大小</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fang ShuHao</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  



  
  

  

  

  

  


  

</body>
</html>
